<template>
  <div>
    <el-dialog title="选择图片" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <div v-loading="tableLoading" class="upload-list-wrap">
        <div v-for="(item,i) in items" :key="i" class="img-box-wrap">
          <i class="i-remove el-icon-circle-close" :title="'删除'" @click="deleteAttachment(item.id)"></i>
          <i class="i-view el-icon-view" :title="'查看'" @click="imageViewModalShow(getOriginalUrl(item.url))"></i>
          <el-image style="width: 120px; height: 120px" :src="item.url" :alt="item.friendlyFileName" :title="item.friendlyFileName"></el-image>
          <el-checkbox v-model="item.isActive" class="i-checkbox" :title="item.friendlyFileName" @change="checkboxChange(item)">{{ item.friendlyFileName }}</el-checkbox>
        </div>
      </div>

      <pagination v-show="totalCount > 0" :total="totalCount" :page-index.sync="q.pageIndex" :page-size.sync="q.pageSize" @pagination="getList"/>

      <el-upload
        ref="upload"
        multiple
        auto-upload
        :action="action"
        :headers="headers"
        :on-success="onSuceess"
        :on-error="onError"
        :on-change="onUploadChange"
        :show-file-list="false"
      >
        <el-button slot="trigger" type="primary" :loading="isSubmitLoading">上传图片</el-button>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="save()">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMyPictureAttachmentPagingList, deleteAttachment } from "@/api/attachment";
import Pagination from "@/components/Pagination";
import { getToken } from "@/utils/auth/token";

export default {
  name: "ImageSelectorDialog",
  components: {
    pagination: Pagination
  },
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    imageSizeClass: {
      type: String,
      default: "-zoom.120.120"
    }
  },
  data() {
    return {
      dialogVisible: false,
      isSubmitLoading: false,
      q: {
        keyWords: undefined,
        imageSizeClass: this.imageSizeClass,
        pageIndex: 1,
        pageSize: 10
      },
      totalCount: 0,
      items: [],
      itemsChecked: [],
      tableLoading: true,
      tableKey: 0,

      uploadDisabled: true,
      action: process.env.VUE_APP_BASE_API + "/Upload/UploadPicture"
    };
  },
  computed: {
    headers() {
      var headers = {};
      headers["Authorization"] = getToken();
      return headers;
    }
  },
  watch: {
    imageSizeClass(newValue) {
      this.q.imageSizeClass = newValue;
    }
  },
  methods: {
    // 打开选择图片和上传图片的Dialog
    open() {
      this.dialogVisible = true;
      this.load();
    },
    // 加载我的图片列表
    load() {
      this.q.pageIndex = 1;
      this.getList();
    },
    // 加载我的图片列表
    getList() {
      this.tableLoading = true;
      getMyPictureAttachmentPagingList(this.q).then(result => {
        result.items.forEach(element => {
          element.isActive = false;
        });

        this.items = [...result.items];
        this.totalCount = result.totalCount;
        this.tableLoading = false;
      });
    },
    checkboxChange(item) {
      if (!this.multiple) {
        this.items.forEach(element => {
          if (item.id !== element.id) {
            element.isActive = false;
          }
        });
      }
    },
    // 将选择的图片返回
    save() {
      const selectedItems = this.items.filter(n => n.isActive) || [];
      if (selectedItems.length < 1) {
        this.$message.warning("请至少选择一张图片");
        return;
      } else {
        var result = selectedItems.map(m => {
          const item = {};
          item.attachmentId = m.id;
          item.url = m.url;
          return item;
        });
        if (this.multiple) {
          this.$emit("save", result);
        } else {
          this.$emit("save", result[0]);
        }
        this.dialogVisible = false;
      }
    },
    // 删除我的图片附件
    deleteAttachment(id) {
      this.$confirm("删除后不可恢复，并且删除该图片的所有关联关系。?", "确定删除该图片吗？", { type: "warning" })
        .then(() => {
          deleteAttachment(id).then(() => {
            this.load();
            this.$message({ message: "删除成功", type: "success" });
          });
        })
        .catch(() => {});
    },
    // 关闭Dialog
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    },

    // 开始上传
    submitUpload() {
      this.isSubmitLoading = true;
      this.$refs.upload.submit();
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    onUploadChange(file, fileList) {
      // const fileName = file.name;
      const fileSize = file.size;
      // if (fileName.indexOf(".xlsx") === -1) {
      //   this.$refs.upload.clearFiles();
      //   this.$message.error("只允许上传.xlsx文件!");
      //   return false;
      // }
      if (fileSize > 1024 * 1024 * 10) {
        this.$refs.upload.clearFiles();
        this.$message.error("上传文件大小不能超过 10MB!");
        return false;
      }
      if (fileList.length > 0) {
        this.uploadDisabled = false;
      }
    },
    // 文件上传成功时的钩子
    onSuceess(response, file, fileList) {
      if (response && response.success) {
        this.$message({ message: "上传成功", type: "success" });
        this.load();
      } else {
        var message = (response && response.error && response.error.message) || "上传出错，请重新上传";
        this.$message({ message: message, type: "error" });
      }
      this.isSubmitLoading = false;
      this.uploadDisabled = true;
    },
    // 文件上传失败时的钩子
    onError(err, file, fileList) {
      if (err) {
        this.$message({ message: "上传失败，请稍候再试", type: "error" });
        this.isSubmitLoading = false;
      }
    }
  }
};
</script>

<style lang="scss">
.upload-list-wrap {
  overflow: hidden;
  .img-box-wrap {
    float: left;
    position: relative;
    width: 120px;
    height: 120px;
    margin: 6px;
    img {
      position: relative;
      width: 100%;
      height: 100%;
    }
    i {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 1;
      width: 25px;
      height: 25px;
      text-align: center;
      line-height: 25px;
      display: none;
      cursor: pointer;
      font-size: 20px;
    }
    .i-remove {
      top: -10px;
      right: -12px;
      color: #f00;
      z-index: 2;
    }
    .i-view {
      top: 0;
      right: 0;
      width: 100%;
      left: 0;
      height: 120px;
      line-height: 120px;
      background: rgba(51, 51, 51, 0.3);
      color: #fff;
      text-align: center;
    }
    &:hover {
      i {
        display: block;
      }
    }
    label {
      position: absolute;
      bottom: 0;
      padding: 2px 5px 3px;
      line-height: normal;
      right: 0;
      left: 0;
      z-index: 1;
      background-color: #333333;
      color: #ffffff;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
